package com.sg.dao.impl;


import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.sg.dao.BaseDAO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.sg.util.Pagination;



@Repository("baseDAO")
@SuppressWarnings("all")
public class BaseDAOImpl<T>  implements BaseDAO<T> {
	private  static Logger log = LogManager.getLogger(BaseDAOImpl.class);
	
	@Autowired
	public SessionFactory sessionFactory;
	
/*	@Autowired
	 @Qualifier("hibernateTemplate")
	public HibernateTemplate hibernateTemplate;*/
	/*@Autowired
	private HibernateTemplate hibernateTemplate; */

/*	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
*/
	private Session getCurrentSession() {
		
		Session session = sessionFactory.getCurrentSession(); 
		//session.setFlushMode(FlushMode.AUTO);
		
		return session;
	}

	public Serializable save(T o) {
		return this.getCurrentSession().save(o);
	}

	public void delete(T o) {
		this.getCurrentSession().delete(o);
	}

	public void update(T o) {
		this.getCurrentSession().update(o);
	}

	public void saveOrUpdate(T o) {
		this.getCurrentSession().saveOrUpdate(o);
	}

	public void flush() {
		this.getCurrentSession().flush();
	}
	
	public List<T> find(String hql) {
		return this.getCurrentSession().createQuery(hql).list();
	}
	
	public List<T> find(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.list();
	}

	public List<T> findAll(Class clazz) {
		String hql = "from " + clazz.getName();
		Query q = this.getCurrentSession().createQuery(hql);
		return q.list();
	}
	
	public List<T> find(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.list();
	}

	public List<T> find(String hql, Object[] param, Integer page, Integer rows) {
		if (page == null || page < 1) {
			page = 1;
		}
		if (rows == null || rows < 1) {
			rows = 10;
		}
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
	}

	public List<T> find(String hql, List<Object> param, Integer page,
			Integer rows) {
		if (page == null || page < 1) {
			page = 1;
		}
		if (rows == null || rows < 1) {
			rows = 10;
		}
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
	}
	
	public Object load(Class<T> clazz, Serializable id) {
		return this.getCurrentSession().load(clazz, id);
	}
	
	public T get(Class<T> c, Serializable id) {
		return (T) this.getCurrentSession().get(c, id);
	}

	public T get(String hql, Object[] param) {
		List<T> l = this.find(hql, param);
		if (l != null && l.size() > 0) {
			return l.get(0);
		} else {
			return null;
		}
	}

	public T get(String hql, List<Object> param) {
		List<T> l = this.find(hql, param);
		if (l != null && l.size() > 0) {
			return l.get(0);
		} else {
			return null;
		}
	}

	public Long count(String hql) {
		return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();
	}

	public Long count(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return (Long) q.uniqueResult();
	}

	public Long count(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return (Long) q.uniqueResult();
	}

	public Integer executeHql(String hql) {
		return this.getCurrentSession().createQuery(hql).executeUpdate();
	}

	public Integer executeHql(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.executeUpdate();
	}

	public Integer executeHql(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.executeUpdate();
	}
	
	public int executeHql(String hql, Map<String,Object> map) {
		Query query = this.getCurrentSession().createQuery(hql);
		setQueryParameters(query, map);	
		return query.executeUpdate();
	}

	public List<T> getByHqlWithKey(String hql, Pagination pagination,
			Map<String, Object> map)  {
		Query query = null;
		query = this.getHqlQuery(hql, map);
		query = this.setQueryParameters(query, pagination);
		return query.list();
	}

	@SuppressWarnings("unchecked")
	public List<T> getByHqlWithIndex(String hql, Pagination pagination, Object... objects) {
		Query query = null;
		query = this.getHqlQuery(hql, objects);
		query = this.setQueryParameters(query, pagination);
		return query.list();
	}
	public Query getHqlQuery(String hql,Map<String,Object> map) {
		Query query = this.createHqlQuery(hql);
		if(map != null){
			return this.setQueryParameters(query, map);
		}
		return query;
	}
	/**
	 * 获取{@link org.hibernate.Query}并设置输入参数值
	 * @param hql
	 * @param objects
	 * @return {@link org.hibernate.Query}
	 * @
	 * @author hanyu Created on 2012-3-29.
	 */
	public Query getHqlQuery(String hql, Object... objects) {
		Query query = this.createHqlQuery(hql);
		if(objects != null && objects.length > 0){
			return this.setQueryParameters(query, objects);
		}
		return query;
	}
	protected Query setQueryParameters(Query query,Pagination pagination) {
		if(pagination != null){
			return query.setFirstResult(pagination.getStart()).setMaxResults(pagination.getPageSize());
		}
		return query;
	}
	/**
	 * 根据“？”占位符和索引值设置参数值。
	 * @param query
	 * @param objects
	 * @return {@link org.hibernate.Query}
	 * @author hanyu Created on 2012-3-29.
	 */
	protected Query setQueryParameters(Query query,Object...objects){
		int index = 0;
		try {
			if(objects != null && objects.length > 0){
				for(Object obj : objects){
					query.setParameter(index, obj);
					index++;
				}
			}
		} catch (HibernateException e) {
			log.error(e.getMessage(),e);
		}
		return query;
	}
	
	/**
	 * 根据“变量名”占位符设置参数值
	 * @param query {@link org.hibernate.Query}
	 * @param map Map<String,Object>
	 * @return {@link org.hibernate.Query}
	 * @author hanyu Created on 2012-3-30.
	 */
	protected Query setQueryParameters(Query query,Map<String,Object> map){
		try {
			if(map != null){
				for(Entry<String,Object> entry : map.entrySet()){
					String key = entry.getKey();
					Object value = entry.getValue();
					if(value instanceof String){
						query.setString(key, value.toString());
					}
					else if(value instanceof Integer){
						query.setInteger(key, Integer.valueOf(value.toString()));
					}
					else if(value instanceof Date){
						query.setParameter(key, value);
					}
					else if(value instanceof Float){
						query.setFloat(key, Float.valueOf(value.toString()));
					}
					else if(value instanceof Double){
						query.setDouble(key, Double.valueOf(value.toString()));
					}
					else if(value instanceof Long){
						query.setLong(key, Long.valueOf(value.toString()));
					}
					
					else if(value instanceof Collection<?>){
						query.setParameterList(key, (Collection<?>) value);
					}
					
					else if(value instanceof Object[]){
						query.setParameterList(key, (Object[]) value);
					}
					
				}
			}
		} catch (NumberFormatException e) {
			log.error("查询过程参数类型转换出错" + e.getMessage(),e);
		}
		return query;
	}
	public int queryCount(String hql) {
		return ((Number)this.createHqlQuery("select count(*) " + hql).uniqueResult()).intValue();
	}
	
	public int queryCount(StringBuffer hql) {
		return ((Number)this.createHqlQuery("select count(*) " + hql.toString()).uniqueResult()).intValue();
	}
	
	public int queryCount(StringBuffer hql,Object...objects) {
		return ((Number)this.getHqlQuery("select count(*) " + hql.toString(),objects).uniqueResult()).intValue();
	}
	
	public int queryCount(StringBuffer hql,Map<String,Object> maps) {
		return ((Number)this.getHqlQuery("select count(*) " + hql.toString(),maps).uniqueResult()).intValue();
	}
	
	public int queryCount(String hql,Map<String,Object> maps) {
		return ((Number)this.getHqlQuery("select count(*) " + hql,maps).uniqueResult()).intValue();
	}
	
	protected Query createHqlQuery(String hql) {
		return this.getCurrentSession().createQuery(hql);
	}

	public List<T> queryHqlByPage(String hql, Pagination pagination,
			Map<String, Object> map) {
		return getByHqlWithKey(hql, pagination, map);
	}

	public List<Object[]> findSomeProperties(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.list();
	}

	@SuppressWarnings("unchecked")
	public List getSomePropertiesByHqlWithKey(String hql, Map<String, Object> map)  {
		Query query = null;
		query = this.getHqlQuery(hql, map);
		return query.list();
	}
	
	public List<Object> findOnePropertie(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.list();
	}
	
	public List<Object[]> findSomeProperties(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.list();
	}

	public Integer executeSql(String sql, Map<String, Object> map) {
		Query query = this.getCurrentSession().createSQLQuery(sql);
		setQueryParameters(query, map);	
		return query.executeUpdate();
	}

	public void mergeItem(T o) {
		 this.getCurrentSession().merge(o);
		
			//this.flush();
	//log.info("更新到数据库中的信息是："+obj.toString());
	}


}